/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-23
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 用户服务
 */
import 'package:chat_client/repositories/auth_repository.dart';
import 'package:chat_client/services/api_service.dart';
import 'package:chat_client/utils/image_picker_helper.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';

class UserService {
  // 单例模式
  UserService._internal();
  static final UserService _instance = UserService._internal();
  static UserService get instance => _instance;

  final ApiService apiService = ApiService.instance;
  final UserRepository userRepository = UserRepository.instance;

  // 获取远程用户个人信息
  Future getRemoteUserInfo() async {
    final response = await apiService.get('/user/info');
    userRepository.setUser(response['data']);
    print(response);
  }

  // 获取本地用户信息
  Future getLocalUserInfo() async {
    final user = await userRepository.getUser();
    print(user);
    return user;
  }

  // 更新用户个人信息
  Future<void> updateUserInfo(Map<String, dynamic> userInfo) async {
    final user = apiService.put('/user/update/', userInfo);
    print(user);
  }

  // 更新用户头像
  Future<void> updateAvatar(XFile imageFile) async {
    MultipartFile? avatarFile;

    try {
      avatarFile = await ImagePickerHelper.convertXFileToMultipart(imageFile);

      final formData = FormData.fromMap({
        'avatar': avatarFile,
      });

      final response = await apiService.postFormData('/user/avatar', formData);
      return response;
    } catch (e) {
      print(e);
      rethrow;
    }
  }

  // 修改用户密码
  Future<void> changePassword(String oldPassword, String newPassword) async {
    final response = await apiService.put('/user/updatePassword',
        {'oldPassword': oldPassword, 'newPassword': newPassword});
    return response;
  }

  // 注销账号
  Future<void> logout(String password) async {
    await apiService.delete('/user/delete', data: {'password': password});
  }
}
